package com.itheima.youdianda.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.entity.SysUser;
import com.itheima.youdianda.entity.YddUser;
import com.itheima.youdianda.service.YddUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-24
 */
@RestController
@RequestMapping("/ydd_user")
@Slf4j
public class YddUserController {
	@Autowired
	private YddUserService yddUserService;

	/**
	 * 根据条件分页查询用户
	 * @param username
	 * @param sex
	 * @param mobile
	 * @param page
	 * @param limit
	 * @return
	 */
	@GetMapping("/list")
	public R<Map<String,Object>> list(String username, String sex, String mobile, @RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String limit){
		log.info("/ydd_user/list,username:{},sex:{},mobile:{},page:{},limit:{}",username,sex,mobile,page,limit);
		Map<String,Object> page1 = yddUserService.listByPage(username,sex,mobile, page,limit);
		return R.success(page1);
	}

	@PostMapping("/add")
	public R<String> add(@RequestBody YddUser yddUser){
		log.info("/ydd_user/add,yddUser:{}",yddUser);
		yddUser.setPassword(DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes()));
		yddUserService.save(yddUser);
		return R.success("添加会员用户成功!");
	}

	@GetMapping("/rowInfo")
	public R<YddUser> rowInfo(@RequestParam String id){
		log.info("/ydd_user/rowInfo,id:{}",id);
		YddUser yddUser = yddUserService.getById(id);
		yddUser.setPassword("");
		return R.success(yddUser);
	}

	@PostMapping("/update")
	public R<String> update(@RequestBody YddUser yddUser){
		log.info("/ydd_user/update,yddUser:{}",yddUser);
		if(yddUser.getPassword() != null){
			yddUser.setPassword(DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes()));
		}
		yddUserService.updateById(yddUser);
		return R.success("修改会员用户成功!");
	}

	@GetMapping("/del")
	public R<String> del(@RequestParam String id){
		log.info("/ydd_user/rowInfo,id:{}",id);
		yddUserService.removeById(id);
		return R.success("删除会员用户成功!");
	}
}
